<?php

namespace App\Http\Controllers\Admin;

use App\Models\System\BootModel;
use App\Models\System\SystemSettingModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\PCHController;

class BootController extends Controller
{
    public function getBootConf(Request $request)
    {
        $data = BootModel::query()->orderBy('sort','asc')->get();
        return self::response($data,200);
    }

    /**
     * 新增/修改 配置
     * @param Request $request
     * @return mixed
     */
    public function modifyBoot(Request $request)
    {
        $input = $request->all();

        $key                        = PCHController::getAllSystemSettingString();
        Redis::del($key);

        if (empty($input['resource'])){
            return self::response(null,'-1','resource is null');
        }

        if (!preg_match('/^(0|\+?[1-9][0-9]*)$/',$input['sort'])){
            return self::response(null,'-1','sort is null');
        }

        if (!in_array($input['type'],[0,1])){
            return self::response(null,'-1','type is null');
        }
        $count = BootModel::query()->where('type','=',$input['type'])->count();
        if (empty($input['id']) && $count > 0) {
            return self::response(null,'-1','只允许添加一个启动页或广告页');
        }
        if (empty($input['id'])){
            unset($input['id']);
            $flag = BootModel::query()->insert($input);
            $msg  = '新增';
        }else{
            $flag = BootModel::query()->where('id',$input['id'])->update($input);
            $msg  = '修改';
        }
        if ($flag){
            return self::response(null,200,$msg.'成功');
        }else{
            return self::response(null,-1,$msg.'失败');
        }
    }


    public function del(Request $request)
    {
        $key                        = PCHController::getAllSystemSettingString();
        Redis::del($key);
        $input = $request->all();
        if (empty($input['id'])){
            return self::response(null,'-1','请选择删除项');
        }
        $flag = BootModel::query()->where('id',$input['id'])->delete();
        if ($flag){
            return self::response(null,200,'修改成功');
        }else{
            return self::response(null,-1,'修改失败');
        }
    }
}
